//
//  LoginViewController.swift
//  FeastBooking
//
//  Created by Imon on 2017/9/17.
//  Copyright © 2017年 Imon. All rights reserved.
//

import UIKit
import RxSwift

class LoginViewController: UIViewController, UITextFieldDelegate {
    
    let userAuthVM = UserAuthViewModel.shared
    let disposeBag = DisposeBag()
    let authManager = AuthManager.share

    var showRegisterView: ((_ sender: UIViewController) -> Void)?
    
    let closeButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "cross"), for: .normal)
        return button
    }()
    
    let titleLabel: UILabel = {
        let label = UILabel()
        label.font = AppFont(size: 24)
        label.textColor = UIColor.gray
        label.text = LanguageHelper.getString(key: "LOGIN")
        return label
    }()
    
    let descriptionLabel: UILabel = {
        let label = UILabel()
        label.font = AppFont(size: 14)
        label.textColor = lightTextColor
        label.text = LanguageHelper.getString(key: "TYPE_USERNAME_PW")
        return label
    }()
    
    let usernameTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = LanguageHelper.getString(key: "USERNAME")
        textField.font = AppFont(size: 15)
        return textField
    }()
    
    let usernameSaperator: UIView = {
        let view = UIView()
        view.backgroundColor = saperatorColor
        return view
    }()
    
    let passwdTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = LanguageHelper.getString(key: "PASSWORD")
        textField.font = AppFont(size: 15)
        textField.isSecureTextEntry = true
        return textField
    }()
    
    let passwdSaperator: UIView = {
        let view = UIView()
        view.backgroundColor = saperatorColor
        return view
    }()
    
    let forgetButton: UIButton = {
        let button = UIButton()
        button.setTitle(LanguageHelper.getString(key: "FORGET_PASSWORD"), for: .normal)
        button.setTitleColor(UIColor.lightGray, for: .normal)
        button.titleLabel?.font = AppFont(size: 12)
        return button
    }()
    
    let tailSaperator: UIView = {
        let view = UIView()
        view.backgroundColor = saperatorColor
        return view
    }()
    
    let registerLabel: UILabel = {
        let label = UILabel()
        label.font = AppFont(size: 12)
        label.textColor = lightTextColor
        label.text = LanguageHelper.getString(key: "NO_ACCOUNT")
        return label
    }()
    
    let registerButton: UIButton = {
        let button = UIButton()
        button.setTitle(LanguageHelper.getString(key: "REGISTER_NOW"), for: .normal)
        button.setTitleColor(UIColor.black, for: .normal)
        button.titleLabel?.font = AppFont(size: 12)
        return button
    }()
    
    @IBOutlet weak var button: UIButton!
    @IBOutlet weak var buttonLayoutConstraint: NSLayoutConstraint!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        
        button.layer.cornerRadius = 3
        button.layer.masksToBounds = true
        
        closeButton.frame = CGRect(x: 15, y: 35, width: 22, height: 22)
        closeButton.addTarget(self, action: #selector(close(_:)), for: .touchUpInside)
        
        let leading: CGFloat = 45
        
        let textMaxSize = CGSize(width: self.view.bounds.width, height: 30)
        let titleSize = TextSize.textSize(text: titleLabel.text!, font: titleLabel.font, maxSize: textMaxSize)
        titleLabel.frame = CGRect(x: leading, y: 85, width: titleSize.width, height: titleSize.height)
        let descriptionSize = TextSize.textSize(text: descriptionLabel.text!, font: descriptionLabel.font, maxSize: textMaxSize)
        descriptionLabel.frame = CGRect(x: leading, y: titleLabel.frame.origin.y + titleLabel.frame.height + 8, width: descriptionSize.width, height: descriptionSize.height)
        
        var currentY = descriptionLabel.frame.origin.y + descriptionLabel.frame.height
        
        usernameTextField.frame = CGRect(x: leading, y: currentY + 30, width: self.view.bounds.width - CGFloat(2) * leading, height: 25)
        
        currentY = usernameTextField.frame.origin.y + usernameTextField.frame.height
        
        usernameSaperator.frame = CGRect(x: leading, y: currentY + 8, width: self.view.bounds.width - CGFloat(2) * leading, height: 0.5)
        
        currentY = usernameSaperator.frame.origin.y + usernameSaperator.frame.height
        
        passwdTextField.frame = CGRect(x: leading, y: currentY + 30, width: self.view.bounds.width - CGFloat(2) * leading, height: 25)
        
        currentY = passwdTextField.frame.origin.y + passwdTextField.frame.height
        
        passwdSaperator.frame = CGRect(x: leading, y: currentY + 8, width: self.view.bounds.width - CGFloat(2) * leading, height: 0.5)
        
        currentY = passwdSaperator.frame.origin.y + passwdSaperator.frame.height
        
        buttonLayoutConstraint.constant = currentY + 45
        
        currentY = currentY + 45 + button.frame.height
        
        let fbSize = TextSize.textSize(text: (forgetButton.titleLabel?.text)!, font: (forgetButton.titleLabel?.font)!, maxSize: textMaxSize)
        
        forgetButton.frame = CGRect(x: passwdSaperator.frame.origin.x + passwdSaperator.frame.width - fbSize.width - 10, y: currentY + 20, width: fbSize.width, height: fbSize.height)
        
        tailSaperator.frame = CGRect(x: 0, y: self.view.bounds.height - 64, width: self.view.bounds.width, height: 0.8)
        
        let rlSize = TextSize.textSize(text: registerLabel.text!, font: registerLabel.font, maxSize: textMaxSize)
        let rbSize = TextSize.textSize(text: (registerButton.titleLabel?.text)!, font: (registerButton.titleLabel?.font)!, maxSize: textMaxSize)
        
        registerLabel.frame = CGRect(x: (self.view.bounds.width - rlSize.width - rbSize.width) / 2, y: self.view.bounds.height - 40, width: rlSize.width, height: rlSize.height)
        registerButton.frame = CGRect(x: registerLabel.frame.origin.x + registerLabel.frame.width, y: self.view.bounds.height - 40, width: rbSize.width, height: rbSize.height)
        
        self.registerButton.addTarget(self, action: #selector(jumpToRegister(_:)), for: .touchUpInside)
        self.forgetButton.addTarget(self, action: #selector(jumpToForgetPW(_:)), for: .touchUpInside)
        
        button.isEnabled = false
        button.addTarget(self, action: #selector(login(_:)), for: .touchUpInside)
        
        self.usernameTextField.delegate = self
        self.passwdTextField.delegate = self
        
        self.usernameTextField.addTarget(self, action: #selector(textFieldValueChange(_:)), for: .editingChanged)
        
        self.passwdTextField.addTarget(self, action: #selector(textFieldValueChange(_:)), for: .editingChanged)
        
        self.view.addSubview(closeButton)
        self.view.addSubview(titleLabel)
        self.view.addSubview(descriptionLabel)
        self.view.addSubview(usernameTextField)
        self.view.addSubview(usernameSaperator)
        self.view.addSubview(passwdTextField)
        self.view.addSubview(passwdSaperator)
        self.view.addSubview(forgetButton)
        self.view.addSubview(tailSaperator)
        self.view.addSubview(registerLabel)
        self.view.addSubview(registerButton)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let point = touch.location(in: self.view)
            if !self.usernameTextField.frame.contains(point) && !self.passwdTextField.frame.contains(point) {
                self.usernameTextField.resignFirstResponder()
                self.passwdTextField.resignFirstResponder()
            }
        }
    }
    
    func textFieldValueChange(_ sender: UITextField) {
        if self.usernameTextField.text != "" && self.passwdTextField.text != "" {
            self.button.isEnabled  = true
        } else {
            self.button.isEnabled = false
        }
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField == self.usernameTextField {
            usernameSaperator.backgroundColor = UIColor.black
        } else {
            passwdSaperator.backgroundColor = UIColor.black
        }
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        if textField == self.usernameTextField {
            usernameSaperator.backgroundColor = saperatorColor
        } else {
            passwdSaperator.backgroundColor = saperatorColor
        }
    }
    
    func jumpToRegister(_ sender: UIButton) {
        if let function = self.showRegisterView {
            function(self)
        }
    }
    
    func jumpToForgetPW(_ sender: UIButton) {
        let forgetPage = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ForgetPWNavigationVC") as! UINavigationController
        self.present(forgetPage, animated: true, completion: nil)
    }
    
    func login(_ sender: UIButton) {
        self.usernameTextField.resignFirstResponder()
        self.passwdTextField.resignFirstResponder()
        
        let username = usernameTextField.text!.trim()
        let password = passwdTextField.text!.trim()
        
        loginIM(username: username, password: password)
    }
    
    func loginApp(username: String, password: String) {
        self.userAuthVM.login(username: username, password: password)
            .subscribe(onNext: { response in
                if let token = response.token {
                    RecentSearchDB.logoutInstance() //退出当前数据库，更换到用户自己的数据库
                    self.authManager.login(token: token)
                    self.dismiss(animated: true, completion: nil)
                } else {
                    if let status = response.status {
                        if status == StatusCode.unauthorized {
                            self.logoutIM() //登錄失敗，登出IM服務器
                            self.showPromptView(message: LanguageHelper.getString(key: "WRONG_USERNAME_PW"), confirmText: LanguageHelper.getString(key: "OK"))
                        } else {
                            self.showPromptView(message: "\(LanguageHelper.getString(key: "FAIL_TO_LOGIN")) \(status)", confirmText: LanguageHelper.getString(key: "OK"))
                        }
                    } else {
                        self.showPromptView(message: "\(LanguageHelper.getString(key: "FAIL_TO_LOGIN"))", confirmText: LanguageHelper.getString(key: "OK"))
                    }
                }
            })
            .addDisposableTo(self.disposeBag)
    }
    
    func loginIM(username: String, password: String) {
        let imPassword = password.md5()
        JMSGUser.login(withUsername: username, password: imPassword) { (result, error) in
            if error == nil {
                UserDefaults.standard.set(username, forKey: kLastUserName)
                UserDefaults.standard.set(username, forKey: kCurrentUserName)
                UserDefaults.standard.set(password, forKey: kCurrentUserPassword)
                self.loginApp(username: username, password: password)
            } else {
                self.showPromptView(message: LanguageHelper.getString(key: "FAIL_TO_LOGIN"), confirmText: LanguageHelper.getString(key: "OK"))
            }
        }
    }
    
    func logoutIM() {
        JMSGUser.logout({ (result, error) in
            JCVerificationInfoDB.shareInstance.queue = nil
            UserDefaults.standard.removeObject(forKey: kCurrentUserName)
            UserDefaults.standard.removeObject(forKey: kCurrentUserPassword)
        })
    }
    
    func close(_ sender: UIButton) {
        self.dismiss(animated: true, completion: nil)
    }
}
